/**
 * 
 */
package cz.cvut.fit.bugtrac.util;

import java.util.ArrayList;
import java.util.Collection;

import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cz.cvut.fit.bugtrac.exception.BugTracException;

/**
 * util class for dozer framework
 * 
 * @author Jaroslav Crhonek
 * 
 */
@Component
public class DozerUtil {

	// injected by spring
	private Mapper mapper;

	/**
	 * map collection - dozer pattern
	 * 
	 * @param sourceList
	 * @param destListClass
	 * @return
	 * @throws Exception
	 */
	public <E> Collection<E> mapList(Collection<?> sourceList,
			Class<E> destListClass) throws BugTracException {
		try {
			Collection<E> result = new ArrayList<E>();

			for (Object e : sourceList) {
				result.add(mapper.map(e, destListClass));
			}

			return result;
		} catch (Exception e) {
			throw new BugTracException("Cannot translate collection: "
					+ e.getMessage(), e);
		}
	}

	/**
	 * map object - dozer pattern
	 * 
	 * @param sourceObject
	 * @param destClass
	 * @return
	 * @throws BugTracException
	 */
	public <E> E mapObject(Object sourceObject, Class<E> destClass)
			throws BugTracException {
		try {
			if (sourceObject == null) {
				return null;
			}
			return mapper.map(sourceObject, destClass);
		} catch (Exception e) {
			throw new BugTracException("Cannot translate object: "
					+ e.getMessage(), e);
		}
	}

	/**
	 * injected by spring
	 */
	@Autowired
	public void setMapper(Mapper mapper) {
		this.mapper = mapper;
	}
}
